package top.whysu.edevice.websocket.config;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.Map;

/**
 * 拦截各种websocket指令，根据指令进行判断
 */
@Component
public class PresenceChannelInterceptor extends ChannelInterceptorAdapter {

    public static final String USER_NAME = "WEBSOCKET_SESSIONID";

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        return message;
    }

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);
        // ignore non-STOMP messages like heartbeat messages
        if (sha.getCommand() == null) {
            return;
        }
        //判断客户端的连接状态
        switch (sha.getCommand()) {
            case CONNECT:
                Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
                if (raw instanceof Map) {
                    //获取请求头参数WEBSOCKET_SESSIONID的值
                    Object name = ((Map) raw).get(USER_NAME);
                    if (name instanceof LinkedList) {
                        String user = ((LinkedList) name).get(0).toString();
                        sha.getSessionAttributes().put(USER_NAME, user);
                        connect(user);
                    }
                }
                break;
            case CONNECTED:
                break;
            case DISCONNECT:
                Object user = sha.getSessionAttributes().get(USER_NAME);
                if (user != null) {
                    disconnect(user.toString(), sha);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean preReceive(MessageChannel channel) {
        return true;
    }

    @Override
    public Message<?> postReceive(Message<?> message, MessageChannel channel) {
        return message;
    }

    /**
     * 连接成功
     * @param user
     */
    private void connect(String user) {

    }

    /**
     * 断开连接
     * @param user
     * @param sha
     */
    private void disconnect(String user, StompHeaderAccessor sha) {
        sha.getSessionAttributes().remove(USER_NAME);
    }
}

